<template>
    <div>
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 角色列表卡片 -->
        <el-card>
            <!-- 添加角色按钮 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRoleDialog">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色展示列表 -->
            <el-table :data="roleList" border stripe >
                <!-- 权限展开显示行 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom',id1===0 ? 'bdtop' : '', 'center']" v-for="(item1,id1) in scope.row.children" :key="item1.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5" >
                                <el-tag closable @close="removeRight(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span="19">
                                <el-row :class="[ i2 === 0 ? '' : 'bdtop', 'center']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                     <!-- 二级权限 -->
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRight(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                     <!-- 三级权限 -->
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRight(scope.row,item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引行 -->
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <!-- 操作 -->
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRoleDialog(scope.row.id)">编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)">删除</el-button>
                        <el-button @click="showRight(scope.row)" size="mini" type="warning" icon="el-icon-setting">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 分配权限的对话框 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="clearDefKeys">
        <!-- 树形控件 -->
            <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref='treeRef'>
            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible=false">取消</el-button>
                <el-button type="primary" @click="setRights">确定</el-button>
            </span>
        </el-dialog>

        <!-- 修改对话框 -->
        <el-dialog title="编辑角色" :visible.sync="editRoleShow" width="70%" @close="editDialogClosed">
            <!-- 修改表单 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRoleShow = false">取 消</el-button>
                <el-button type="primary" @click="editRole">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改对话框 -->
        <el-dialog title="添加角色" :visible.sync="addRoleShow" width="70%" @close="addDialogClosed">
            <!-- 修改表单 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRoleShow = false">取 消</el-button>
                <el-button type="primary" @click="addRole">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
  created () {
    // 获取角色列表
    this.getRolesList()
  },
  data () {
    return {
      roleList: [],
      setRightDialogVisible: false,
      rightList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      roleId: '',
      // 编辑角色的数据
      // /控制修改角色.属性对话框的显示或隐藏
      editRoleShow: false,
      // 修改参数.属性对话框中的表单
      editForm: {
        roleName: '',
        roleDesc: ''
      },
      // 修改表单的验证规则
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 8, message: '角色名称长度在2到8个字之间', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 15, message: '角色描述长度在2到15个字之间', trigger: 'blur' }
        ]
      },

      // 控制添加角色.属性对话框的显示或隐藏
      addRoleShow: false,
      // 添加角色.属性对话框中的表单
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加表单的验证规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 8, message: '角色名称长度在2到8个字之间', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 15, message: '角色描述长度在2到15个字之间', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      };
      this.roleList = res.data
    },
    // 删除权限
    async removeRight (role, id) {
      // 弹框询问是否删除
      const right = await this.$confirm('是否确认删除该权限？', '警示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (right !== 'confirm') {
        return this.$message.info('取消删除')
      };
      const { data: res } = await this.$axios.delete(`roles/${role.id}/rights/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('权限删除失败！')
      };
      role.children = res.data
    },
    // 展示分配权限
    async showRight (role) {
      this.roleId = role.id
      const { data: res } = await this.$axios.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      };
      this.rightList = res.data
      this.getKey(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    getKey (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      };
      node.children.forEach(element => this.getKey(element, arr))
    },
    clearDefKeys () {
      this.defKeys = []
    },
    // 给角色分配权限
    async setRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$axios.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败!')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    async deleteRole (id) {
      const right = await this.$confirm('请问是否确认删除？', '删除提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => { err })
      if (right !== 'confirm') {
        return this.$message.info('已经取消删除')
      };
      const { data: res } = await this.$axios.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数数据失败')
      };
      this.$message.success('删除成功')
      this.getRolesList()
    },
    // 编辑按钮点击事件
    async editRoleDialog (id) {
      const { data: res } = await this.$axios.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.editForm = res.data
      this.roleId = res.data.roleId
      this.editRoleShow = true
    },
    // 监听编辑角色对话框关闭事件
    editDialogClosed () {
      // 重置输入框
      this.$refs.editFormRef.resetFields()
    },
    // 编辑角色提交
    editRole () {
      // 先表单验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.put('roles/' + this.roleId, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数数据失败')
        };
        this.$message.success('修改参数数据成功')
        this.editRoleShow = false
        this.getRolesList()
      })
    },

    // 添加角色对话框
    addRoleDialog () {
      this.addRoleShow = true
    },
    // 添加角色对话框关闭事件
    addDialogClosed () {
      // 重置输入框
      this.$refs.addFormRef.resetFields()
    },
    // 添加角色提交函数
    async addRole () {
      const { data: res } = await this.$axios.post('roles', {
        roleName: this.addForm.roleName,
        roleDesc: this.addForm.roleDesc
      })
      if (res.meta.status !== 201) {
        return this.$message.error('添加角色失败')
      };
      this.$message.success('添加角色成功')
      this.addRoleShow = false
      this.getRolesList()
    }
  }
}
</script>
<style scoped lang="less">
.el-tag{
    margin:5px;
}
.bdbottom{
    border-bottom: 1px solid #eee;
}
.bdtop{
    border-top: 1px solid #eee;
}
.center{
    display: flex;
    align-items: center;
}
</style>
